import Vue from "vue";
import VueRouter from "vue-router";
// 引入登录组件
import Login from "@/views/login";
import Layout from "@/views/Layout";
import Home from "@/views/Home";
import Question from "@/views/Question";
import Video from "@/views/Video";
import User from "@/views/User";
import Search from "@/views/Search";
import Result from "@/views/Search/result.vue";
import Article from "@/views/Article";
// 引入vuex
import store from "@/store/index.js";
// 测试组件
// import Test from "@/test/father.vue";
// import Test from "@/test/index.vue";
// 解决重复点击路由控制台报错的问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
};

Vue.use(VueRouter);

const routes = [
  {
    path: "/login",
    name: "Login",
    component: Login
  },
  {
    path: "/",
    name: "Layout",
    component: Layout,
    children: [
      {
        path: "/",
        name: "Home",
        component: Home
      },
      {
        path: "/question",
        name: "question",
        component: Question
      },
      {
        path: "/video",
        name: "video",
        component: Video
      },
      {
        path: "/user",
        name: "user",
        component: User
      }
    ]
  },
  {
    path: "/search",
    name: "search",
    component: Search
  },
  {
    path: "/search/result",
    name: "result",
    component: Result
  },
  {
    path: "/articledetail/:id",
    name: "articleDetail",
    component: Article
  },
  {
    path: "/user/edituser",
    name: "edituser",
    component: () => import("@/views/User/EditUser.vue")
  },
  {
    path: "/user/xaiozhi",
    name: "xiaozhi",
    component: () => import("@/views/User/Xiaozhi.vue")
  }
  // {
  //   path: "/test",
  //   name: "test",
  //   component: Test
  // }
  // {
  //   path: "/about",
  //   name: "About",
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () =>
  //     import(/* webpackChunkName: "about" */ "../views/About.vue")
  // }
];

const router = new VueRouter({
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  if (to.fullPath === "/user") {
    let token = store.state.tokenInfo.token;
    // 判断token是否存在
    if (token) {
      next();
    } else {
      console.log(to.path, "路由");
      next("/login?backto=" + to.fullPath);
    }
  } else {
    next();
  }
});

export default router;
